const { app, BrowserWindow, ipcMain, shell } = require('electron')
// include the Node.js 'path' module at the top of your file
const douyinpb = require('./douyin/main.js')//protobuf转json
const tiktokpb = require('./tiktok/main.js')//protobuf转json
const weixinpb = require('./weixin/main.js')//微信弹幕解析

// 全局变量
let mainWindow = null
let liveRoom = null
let currentPlatformInfo = {
  name: null,
  url: null
}
const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      //preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false
    },
    autoHideMenuBar: true,
  })
  mainWindow.loadFile('./page/index.html')
  //mainWindow.webContents.openDevTools()
}

// 忽略SSL证书错误（用于解决SSL握手失败问题）
app.commandLine.appendSwitch('--ignore-certificate-errors')
app.commandLine.appendSwitch('--ignore-ssl-errors')
app.commandLine.appendSwitch('--ignore-certificate-errors-spki-list')
app.commandLine.appendSwitch('--disable-web-security')

app.whenReady().then(() => {
  createWindow()
  // 启动WebSocket服务器
  try {
    // websocketServer模块会自动启动服务器
    console.log('WebSocket服务器已在端口12011启动')
  } catch (error) {
    console.error('WebSocket服务器启动失败:', error)
  }

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// IPC通信处理
ipcMain.handle('open-live-room', async (event, url) => {
  try {
    // 检查是否已经有直播间窗口打开
    if (liveRoom && !liveRoom.isDestroyed()) {
      // 如果已经有直播间窗口，先关闭它
      liveRoom.close()
      liveRoom = null
    }

    // 验证URL格式
    if (!url || typeof url !== 'string' || !url.trim()) {
      throw new Error('请输入有效的直播间网址')
    }

    // 检查是否为支持的平台
    const supportedPlatforms = ['douyin.com', 'tiktok.com', 'kuaishou.com', 'bilibili.com', 'channels.weixin.qq.com']
    const isSupported = supportedPlatforms.some(platform => url.includes(platform))

    if (!isSupported) {
      throw new Error('暂不支持该平台，请使用抖音、TikTok、快手、BiliBili或视频号的直播间网址')
    }

    // 打开直播间
    openLiveRoom(url.trim())
    return { success: true, message: '直播间已打开' }
  } catch (error) {
    console.error('打开直播间失败:', error)
    return { success: false, message: error.message }
  }
})

// 处理平台信息更新
ipcMain.handle('update-current-platform', async (event, platformInfo) => {
  try {
    currentPlatformInfo = {
      name: platformInfo.name,
      url: platformInfo.url
    }
    当前平台 = platformInfo.name
    console.log(`当前连接平台已更新: ${platformInfo.name} - ${platformInfo.url}`)
    return { success: true }
  } catch (error) {
    console.error('更新平台信息失败:', error)
    return { success: false, message: error.message }
  }
})

// 获取当前平台信息
ipcMain.handle('get-current-platform', async () => {
  return {
    success: true,
    platform: currentPlatformInfo
  }
})


// 打开直播间
function openLiveRoom(url) {
  liveRoom = new BrowserWindow({
    autoHideMenuBar: true, // 自动隐藏菜单栏
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      // webSecurity: false, // 禁用web安全策略以解决SSL问题
      // allowRunningInsecureContent: true // 允许运行不安全内容
      partition: 'persist:liveroom', // 使用持久化分区来保存缓存
      enableRemoteModule: false
    }
  })

  // 设置User-Agent（在webContents级别设置更有效）
  liveRoom.webContents.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0')

  // 监听窗口关闭事件
  liveRoom.on('closed', () => {
    liveRoom = null
    // 清空当前平台信息
    currentPlatformInfo = {
      name: null,
      url: null
    }
    当前平台 = "抖音" // 重置为默认值

    // 通知渲染进程直播间已关闭
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send('live-room-closed')
    }

    console.log('直播间已关闭，平台信息已清空')
  })

  liveRoom.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  liveRoom.loadURL(url)

  //TikTok读取数据
  // if (url.includes('tiktok')) {
  //   liveRoom.webContents.on('dom-ready', () => {
  //     liveRoom.webContents
  //       .executeJavaScript(
  //         `
  //           const user = JSON.parse(document.getElementById("SIGI_STATE").innerText).LiveRoom.liveRoomUserInfo.user;
  //           user;
  //       `
  //       )
  //       .then((user) => {
  //         const info = user
  //         info['from'] = 'tiktok'
  //         mainWindow.webContents.send('send-anchor-data', info)
  //       })
  //       .catch((error) => {
  //         console.error('No anchor information was obtained', error)
  //       })
  //   })
  // }

  //鼠标随机移动
  const mouseID = setInterval(() => {
    if (liveRoom) {
      const { width, height } = liveRoom.getBounds()
      const newX = Math.floor(Math.random() * width)
      const newY = Math.floor(Math.random() * height)
      liveRoom.webContents.sendInputEvent({
        type: 'mouseMove',
        x: newX,
        y: newY
      })
    }
  }, 5000)



  //不知道干啥用的，等等再说
  try {
    liveRoom.webContents.debugger.attach('1.1')
    console.log('yes, I can')
  } catch (err) {
    console.log('Debugger attach failed: 123456', err)
  }


  //可能是弹幕解析相关代码
  liveRoom.webContents.debugger.on(
    'message',
    async (_event, method, params) => {
      //Websocket拦截
      if (method === 'Network.webSocketFrameReceived') {
        const payloadData = params.response.payloadData
        const buff = Buffer.from(payloadData, 'base64')
        if (currentPlatformInfo.name == "抖音") {
          douyinpb.pb2json(buff);//解析弹幕数据
        }
        if (currentPlatformInfo.name == "TikTok") {
          tiktokpb.pb2json(buff);//解析弹幕数据
        }
      }
      //HTTP拦截
      if (method === 'Network.responseReceived') {
        //console.log(method,params)
        if (currentPlatformInfo.name == "视频号") {
          if (params.response.url.includes('/live/msg')) {
            try {
              const response = await liveRoom.webContents.debugger.sendCommand(
                'Network.getResponseBody',
                {
                  requestId: params.requestId
                }
              )
              weixinpb.p2j(params.response.url, response.body)
            } catch (error) {
              console.error('weixin error:', error)
            }
          }
        }
        //抖音相关
        if (
          params.response.url.includes('douyin.com/webcast/room/web/enter/?aid=')) {
          try {
            const response = await liveRoom.webContents.debugger.sendCommand(
              'Network.getResponseBody',
              {
                requestId: params.requestId
              }
            )
            const info = JSON.parse(response.body).data.user
            info['from'] = 'douyin'
            mainWindow.webContents.send('send-anchor-data', info)
            // console.log('douyin', info)
          } catch (error) {
            console.error('douyin error:', error)
            // mainWindow.webContents.send('get-anchor-fail')
            // closeLiveRoom()
          }
        }
      }
    }
  )
  liveRoom.webContents.debugger.sendCommand('Network.enable')
}

